package org.zizi.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.zizi.dao.UserDao;
import org.zizi.manager.impl.DaoManager;
import org.zizi.modal.User;
import org.zizi.util.Options;
import org.zizi.util.PasswordChecher;

public class LoginManager implements Manager
{
	/** Session -> Login */
	private Map<String, String> logins = new ConcurrentHashMap<String, String>();
	/** Login -> 用户信息 */
	private Map<String, User> users = new ConcurrentHashMap<String, User>();
	
	public void initialize(Options options) throws Exception
	{
	}

	public void destory()
	{
	}
	
	public boolean login(String session, String login, String password) throws Exception
	{
		boolean ok = true;
		
		//get user by login
		UserDao dao = Managers.get(DaoManager.class).getDao(UserDao.class);
		User u = dao.getUser(login);
		
		if (u == null) ok = false;	//登陆号不存在
		if (u != null && !PasswordChecher.check(password, u.getPassword())) ok = false;	//密码错误
		
		//成功登陆
		synchronized (this)
		{
			logins.put(session, login);
			if (ok) users.put(login, u);
		}
		
		return ok;
	}
	
	public void remove(String session)
	{
		if (session == null) return;
		
		synchronized (this)
		{
			String login = logins.remove(session);
			if (login != null) users.remove(login);
		}
	}
	
	public String getLogin(String session)
	{
		if (session == null) return null;
		return logins.get(session);
	}
	
	public User getUserByLogin(String login)
	{
		if (login == null) return null;
		return users.get(login);
	}
	
	public User getUser(String session)
	{
		String login = getLogin(session);
		if (login == null) return null;
		
		return users.get(login);
	}
	
	public static boolean isLogin(String session)
	{
		return Managers.get(LoginManager.class).getUser(session) != null;
	}
}
